package com.map;

import java.util.ArrayList;
import java.util.List;

import static com.map.Constant.EXTENDS_3857;
import static com.map.Point.MectorToWgs84;

/**
 * Description: load
 * <p>
 * Created by 韩博 on 2020/4/26 14:41
 */
public class TileIndex {
    private Integer x;
    private Integer y;
    private Integer z;

    public TileIndex(Integer x, Integer y, Integer z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public Integer getX() {
        return x;
    }

    public void setX(Integer x) {
        this.x = x;
    }

    public Integer getY() {
        return y;
    }

    public void setY(Integer y) {
        this.y = y;
    }

    public Integer getZ() {
        return z;
    }

    public void setZ(Integer z) {
        this.z = z;
    }

    /**
     * 通过范围计算瓦片行列号
     * @param min
     * @param max
     * @param level
     * @return
     */
    public static List<TileIndex> GetTiles(Point min, Point max, Integer level) {
        List<TileIndex> list = new ArrayList<>();
        double tile_size = EXTENDS_3857 / Math.pow(2, level - 1);
        Integer x1 = (int) Math.ceil((min.getX() + EXTENDS_3857) / tile_size) - 1;//起始X,减1是因为从0开始
        Integer x2 = (int) Math.ceil((max.getX() + EXTENDS_3857) / tile_size) - 1;//终止X

        Integer y1 = 0, y2 = 0;
        y1 = (int)Math.ceil((EXTENDS_3857 - max.getY()) / tile_size) - 1;//起始y
        y2 = (int)Math.ceil((EXTENDS_3857 - min.getY()) / tile_size) - 1;//终止y

        //防止计算产生负值
        if (x1 < 0) {
            x1 = 0;
        }
        if (x2 < 0) {
            x2 = 0;
        }
        if (y1 < 0) {
            y1 = 0;
        }
        if (y2 < 0) {
            y2 = 0;
        }
        for (Integer j = x1; j <= x2; j++) {
            for (Integer k = y1; k <= y2; k++) {
                list.add(new TileIndex(j,k,level));
                // sendDownCmd(j,k,level);
                //j就是url中的x,
                //k就是url中的y,
                //level就是地图等级对应url中的z
            }
        }

        return list;
    }


    public static void test(TileIndex tileIndex){
        double tile_size = EXTENDS_3857 / Math.pow(2, tileIndex.getZ() - 1);
        double yMin=EXTENDS_3857 -(tileIndex.getY()+1)*tile_size;
        double yMax=EXTENDS_3857 -(tileIndex.getY()+2)*tile_size;
        double xMin=(tileIndex.getX()+1)*tile_size-EXTENDS_3857;
        double xMax=(tileIndex.getX()+2)*tile_size-EXTENDS_3857;

//        double yMin=-EXTENDS_3857 +(tileIndex.getY()+1)*tile_size;
//        double yMax=-EXTENDS_3857 +(tileIndex.getY()+2)*tile_size;
//        double xMin=(tileIndex.getX()+1)*tile_size-EXTENDS_3857;
//        double xMax=(tileIndex.getX()+2)*tile_size-EXTENDS_3857;

        System.out.println(MectorToWgs84(new Point(xMin,yMin)));
        System.out.println(MectorToWgs84(new Point(xMax,yMax)));
    }
}
